<!doctype html>



  


<html class="theme-next mist use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css"/>




  <link href="//fonts.googleapis.com/css?family=Lato:300,400,700,400italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">



<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=0.5.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="关系型数据库,MySQL," />





  <link rel="alternate" href="/atom.xml" title="Joshua Shaw之秘密花园" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=0.5.0" />






<meta name="description" content="0x00前言本书讲述到定稿前的MySQL5.5版，所以下面内容的适用范围止步于MySQL5.5。本文仅仅强调书中讲述的重中之重，以便快速查阅，详细的内容还请认真阅读书本和MySQL的官方文档。

0x01 为什么查询速度会慢查询性能低下的最基本的原因是访问的数据太多。

查询不需要的记录。使用LIMIT来限制。
多表关联时返回全部列。
总是取出全部列。可简化开发或者有利于某种缓存机制。
重复查询相">
<meta property="og:type" content="article">
<meta property="og:title" content="《高性能MySQL》の查询性能优化">
<meta property="og:url" content="http://joshshaw.github.io/2016/05/04/《高性能MySQL》の查询性能优化/index.html">
<meta property="og:site_name" content="Joshua Shaw之秘密花园">
<meta property="og:description" content="0x00前言本书讲述到定稿前的MySQL5.5版，所以下面内容的适用范围止步于MySQL5.5。本文仅仅强调书中讲述的重中之重，以便快速查阅，详细的内容还请认真阅读书本和MySQL的官方文档。

0x01 为什么查询速度会慢查询性能低下的最基本的原因是访问的数据太多。

查询不需要的记录。使用LIMIT来限制。
多表关联时返回全部列。
总是取出全部列。可简化开发或者有利于某种缓存机制。
重复查询相">
<meta property="og:updated_time" content="2016-05-04T08:08:49.830Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="《高性能MySQL》の查询性能优化">
<meta name="twitter:description" content="0x00前言本书讲述到定稿前的MySQL5.5版，所以下面内容的适用范围止步于MySQL5.5。本文仅仅强调书中讲述的重中之重，以便快速查阅，详细的内容还请认真阅读书本和MySQL的官方文档。

0x01 为什么查询速度会慢查询性能低下的最基本的原因是访问的数据太多。

查询不需要的记录。使用LIMIT来限制。
多表关联时返回全部列。
总是取出全部列。可简化开发或者有利于某种缓存机制。
重复查询相">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Mist',
    sidebar: {"position":"left","display":"always"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>

  <title> 《高性能MySQL》の查询性能优化 | Joshua Shaw之秘密花园 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  



  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?99d95abecc387f2aa83d123804dddd4c";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>








  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">Joshua Shaw之秘密花园</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">成就自己</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-home fa-fw"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-user fa-fw"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-th fa-fw"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-archive fa-fw"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-tags fa-fw"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                《高性能MySQL》の查询性能优化
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-05-04T15:07:23+08:00" content="2016-05-04">
              2016-05-04
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/计算机科学/" itemprop="url" rel="index">
                    <span itemprop="name">计算机科学</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2016/05/04/《高性能MySQL》の查询性能优化/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2016/05/04/《高性能MySQL》の查询性能优化/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="0x00前言"><a href="#0x00前言" class="headerlink" title="0x00前言"></a>0x00前言</h2><p>本书讲述到定稿前的MySQL5.5版，所以下面内容的适用范围止步于MySQL5.5。本文仅仅强调书中讲述的重中之重，<br>以便快速查阅，详细的内容还请认真阅读书本和MySQL的官方文档。</p>
<hr>
<h2 id="0x01-为什么查询速度会慢"><a href="#0x01-为什么查询速度会慢" class="headerlink" title="0x01 为什么查询速度会慢"></a>0x01 为什么查询速度会慢</h2><p>查询性能低下的最基本的原因是访问的数据太多。</p>
<ul>
<li>查询不需要的记录。使用LIMIT来限制。</li>
<li>多表关联时返回全部列。</li>
<li>总是取出全部列。可简化开发或者有利于某种缓存机制。</li>
<li>重复查询相同的数据。</li>
</ul>
<p><strong>响应时间：包括服务时间和排队时间，排队时间最常见和重要的是IO和锁等待。</strong><br><strong>快速上限估计：获得一个大概参考值来判断当前响应时间是不是一个合理的值。</strong><br>扫描后返回行数和访问类型：</p>
<ol>
<li>做一个关联查询时，服务器必须要扫描多行才能生成结果集中的一行。扫描的行数对返回的行数的比率通常很小，<br>如果在1:1到10:1之间是比较好的。</li>
<li>全表扫描 &lt; 索引扫描 &lt; 范围扫描 &lt; 唯一索引查询 &lt; 常数引用。优秀的索引能极大地提高扫描的速度。</li>
</ol>
<p>应用WHERE条件时从好到坏依次为：</p>
<ol>
<li>在索引中过滤不匹配的记录，在存储引擎层完成。</li>
<li>使用索引覆盖扫描，在MySQL服务器层完成，无需回到数据表进行查询。</li>
<li>从数据表返回数据，MySQL需要先从数据表读出记录然后过滤，在MySQL服务器层完成。</li>
</ol>
<p><strong>因此，不需要的数据应该尽可能地从越底层被过滤，如果数据还要提升到服务器层（而不是在存储引擎层）进行过滤<br>那么就会对性能有影响。</strong></p>
<p>如果发现查询需要扫描大量的数据但是只返回少数的行，优化技巧如下：</p>
<ul>
<li>使用索引覆盖扫描</li>
<li>使用单独的汇总表</li>
<li>重写查询语句</li>
</ul>
<hr>
<a id="more"></a>
<h2 id="0x02重构查询"><a href="#0x02重构查询" class="headerlink" title="0x02重构查询"></a>0x02重构查询</h2><ol>
<li>设计查询时，是否需要将一个复杂的查询分成多个简单的查询。</li>
<li>如果是事务型引擎，很多时候小事务能够更高效。</li>
<li>分解关联查询的优势和使用场景：<ul>
<li>优势<ul>
<li>让缓存的效率更高</li>
<li>将查询分解后，执行单个查询可以减少锁的竞争</li>
<li>查询本身效率也可能有所提升</li>
<li>可以减少冗余记录的查询</li>
</ul>
</li>
<li>使用场景<ul>
<li>当应用能方便地缓存单个查询的结果</li>
<li>可以将数据分布到不同的MySQL服务器上</li>
<li>能够使用IN()方式代替关联查询</li>
<li>当查询中使用同一个数据表</li>
</ul>
</li>
</ul>
</li>
</ol>
<hr>
<h2 id="0x03查询执行的步骤"><a href="#0x03查询执行的步骤" class="headerlink" title="0x03查询执行的步骤"></a>0x03查询执行的步骤</h2><ol>
<li>客户端发送一条查询给服务器。  <ul>
<li><strong>半双工的。</strong></li>
<li>将结果缓存还是直接获取？数据量大时，直接获取。</li>
</ul>
</li>
<li>服务器先检查查询缓存，如果命中了缓存，则立即返回存储在缓存中的结果，否则进入下一阶段。<ul>
<li>查询缓存中的查询即是只有一个字节不同，那么就不会匹配缓存结果。</li>
</ul>
</li>
<li>服务器端进行SQL解析、预处理，再由优化器生成对应的执行计划。<ul>
<li>SQL语句结构相同而参数不同时，使用<code>prepareStatment()</code>对大量相同的查询有利。</li>
<li>优化器是通过成本计算而不是最短时间来选择优化的</li>
<li>优化策略包括静态（编译）优化和动态（运行）优化</li>
<li>MySQL的优化器是自动执行的，不需要认为干预，一般运行良好</li>
<li>需要认为干预时可以使用HINT提示，提前要做好测试</li>
</ul>
</li>
<li>MySQL根据优化器生成的执行计划，调用存储引擎的API来执行查询。<ul>
<li>MySQL的执行计划总是一颗左侧深度优先的树</li>
<li>关联操作时会自动优化执行，关联的表多时采用贪心策略</li>
</ul>
</li>
<li>将结果返回给客户端。<ul>
<li>一个增量、逐步返回的过程，好处包括：<ul>
<li>服务器端无须存储太多的结果，节省内存</li>
<li>让MySQL客户端第一时间获得返回的结果</li>
</ul>
</li>
</ul>
</li>
</ol>
<hr>
<h2 id="0x04一些特定的优化策略"><a href="#0x04一些特定的优化策略" class="headerlink" title="0x04一些特定的优化策略"></a>0x04一些特定的优化策略</h2><p>具体看书，通用性不大</p>
<hr>
<h2 id="0x05一个案例学习"><a href="#0x05一个案例学习" class="headerlink" title="0x05一个案例学习"></a>0x05一个案例学习</h2><p>使用MySQL构建一个队列表时，不要只用一张表保存整个队列，队列中包括未处理，正在处理和已经处理的数据，<br>而是使用两个（或者以上）表，让未处理的表保持数据量较少，而已处理的数据表为历史数据表。</p>
<hr>
<h2 id="0x06小结"><a href="#0x06小结" class="headerlink" title="0x06小结"></a>0x06小结</h2><p>一般来说，先实现再优化，但是要有预见性。所以，切记自己的需求。</p>
<hr>
<h2 id="引用"><a href="#引用" class="headerlink" title="引用"></a>引用</h2><p> <a href="https://book.douban.com/subject/4241826/" target="_blank" rel="external">《高性能MySQL · 第三版》</a></p>

      
    </div>

    <div>
      
        
      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/关系型数据库/" rel="tag">#关系型数据库</a>
          
            <a href="/tags/MySQL/" rel="tag">#MySQL</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/04/29/《高性能MySQL》の创建高性能的索引/" rel="next" title="《高性能MySQL》の创建高性能的索引">
                <i class="fa fa-chevron-left"></i> 《高性能MySQL》の创建高性能的索引
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/05/04/《高性能MySQL》指南摘要/" rel="prev" title="《高性能MySQL》指南摘要">
                《高性能MySQL》指南摘要 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_tsina"></a>
  <a class="jiathis_button_tqq"></a>
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_douban"></a>
  <a class="jiathis_button_renren"></a>
  <a class="jiathis_button_qzone"></a>
  <a class="jiathis_button_kaixin001"></a>
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2016/05/04/《高性能MySQL》の查询性能优化/"
           data-title="《高性能MySQL》の查询性能优化" data-url="http://joshshaw.github.io/2016/05/04/《高性能MySQL》の查询性能优化/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.png"
               alt="Joshua Shaw" />
          <p class="site-author-name" itemprop="name">Joshua Shaw</p>
          <p class="site-description motion-element" itemprop="description"></p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">20</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">6</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">26</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/joshuashawnetlab" target="_blank">
                  
                    <i class="fa fa-globe"></i> Github_1
                  
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://github.com/joshshaw" target="_blank">
                  
                    <i class="fa fa-globe"></i> Github_2
                  
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/u/2622463195" target="_blank">
                  
                    <i class="fa fa-weibo"></i> Weibo
                  
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://my.oschina.net/joshuashaw" target="_blank">
                  
                    <i class="fa fa-globe"></i> OSChina
                  
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.zhihu.com/people/xiao-chong-chong-41" target="_blank">
                  
                    <i class="fa fa-globe"></i> Zhihu
                  
                </a>
              </span>
            
          
        </div>

        
        

        
        <div class="links-of-blogroll motion-element">
          
        </div>

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc-indicator-top post-toc-indicator">
            <i class="fa fa-angle-double-up"></i>
          </div>
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#0x00前言"><span class="nav-number">1.</span> <span class="nav-text">0x00前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#0x01-为什么查询速度会慢"><span class="nav-number">2.</span> <span class="nav-text">0x01 为什么查询速度会慢</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#0x02重构查询"><span class="nav-number">3.</span> <span class="nav-text">0x02重构查询</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#0x03查询执行的步骤"><span class="nav-number">4.</span> <span class="nav-text">0x03查询执行的步骤</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#0x04一些特定的优化策略"><span class="nav-number">5.</span> <span class="nav-text">0x04一些特定的优化策略</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#0x05一个案例学习"><span class="nav-number">6.</span> <span class="nav-text">0x05一个案例学习</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#0x06小结"><span class="nav-number">7.</span> <span class="nav-text">0x06小结</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#引用"><span class="nav-number">8.</span> <span class="nav-text">引用</span></a></li></ol></div>
            
          </div>
          <div class="post-toc-indicator-bottom post-toc-indicator">
            <i class="fa fa-angle-double-down"></i>
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Joshua Shaw</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="http://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>



      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  


  




<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  <script type="text/javascript" src="/vendors/velocity/velocity.min.js"></script>

  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js"></script>

  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=0.5.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=0.5.0"></script>



  
  

  
  
<script type="text/javascript" src="/js/src/scrollspy.js?v=0.5.0"></script>

<script type="text/javascript" id="sidebar.toc.highlight">
  $(document).ready(function () {
    var tocSelector = '.post-toc';
    var $tocSelector = $(tocSelector);
    var activeCurrentSelector = '.active-current';

    $tocSelector
      .on('activate.bs.scrollspy', function () {
        var $currentActiveElement = $(tocSelector + ' .active').last();

        removeCurrentActiveClass();
        $currentActiveElement.addClass('active-current');

        $tocSelector[0].scrollTop = $currentActiveElement.position().top;
      })
      .on('clear.bs.scrollspy', function () {
        removeCurrentActiveClass();
      });

    function removeCurrentActiveClass () {
      $(tocSelector + ' ' + activeCurrentSelector)
        .removeClass(activeCurrentSelector.substring(1));
    }

    function processTOC () {
      getTOCMaxHeight();
      toggleTOCOverflowIndicators();
    }

    function getTOCMaxHeight () {
      var height = $('.sidebar').height() -
                   $tocSelector.position().top -
                   $('.post-toc-indicator-bottom').height();

      $tocSelector.css('height', height);

      return height;
    }

    function toggleTOCOverflowIndicators () {
      tocOverflowIndicator(
        '.post-toc-indicator-top',
        $tocSelector.scrollTop() > 0 ? 'show' : 'hide'
      );

      tocOverflowIndicator(
        '.post-toc-indicator-bottom',
        $tocSelector.scrollTop() >= $tocSelector.find('ol').height() - $tocSelector.height() ? 'hide' : 'show'
      )
    }

    $(document).on('sidebar.motion.complete', function () {
      processTOC();
    });

    $('body').scrollspy({ target: tocSelector });
    $(window).on('resize', function () {
      if ( $('.sidebar').hasClass('sidebar-active') ) {
        processTOC();
      }
    });

    onScroll($tocSelector);

    function onScroll (element) {
      element.on('mousewheel DOMMouseScroll', function (event) {
          var oe = event.originalEvent;
          var delta = oe.wheelDelta || -oe.detail;

          this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
          event.preventDefault();

          toggleTOCOverflowIndicators();
      });
    }

    function tocOverflowIndicator (indicator, action) {
      var $indicator = $(indicator);
      var opacity = action === 'show' ? 1 : 0;
      $indicator.velocity ?
        $indicator.velocity('stop').velocity({
          opacity: opacity
        }, { duration: 100 }) :
        $indicator.stop().animate({
          opacity: opacity
        }, 100);
    }

  });
</script>

<script type="text/javascript" id="sidebar.nav">
  $(document).ready(function () {
    var html = $('html');
    var TAB_ANIMATE_DURATION = 200;
    var hasVelocity = $.isFunction(html.velocity);

    $('.sidebar-nav li').on('click', function () {
      var item = $(this);
      var activeTabClassName = 'sidebar-nav-active';
      var activePanelClassName = 'sidebar-panel-active';
      if (item.hasClass(activeTabClassName)) {
        return;
      }

      var currentTarget = $('.' + activePanelClassName);
      var target = $('.' + item.data('target'));

      hasVelocity ?
        currentTarget.velocity('transition.slideUpOut', TAB_ANIMATE_DURATION, function () {
          target
            .velocity('stop')
            .velocity('transition.slideDownIn', TAB_ANIMATE_DURATION)
            .addClass(activePanelClassName);
        }) :
        currentTarget.animate({ opacity: 0 }, TAB_ANIMATE_DURATION, function () {
          currentTarget.hide();
          target
            .stop()
            .css({'opacity': 0, 'display': 'block'})
            .animate({ opacity: 1 }, TAB_ANIMATE_DURATION, function () {
              currentTarget.removeClass(activePanelClassName);
              target.addClass(activePanelClassName);
            });
        });

      item.siblings().removeClass(activeTabClassName);
      item.addClass(activeTabClassName);
    });

    $('.post-toc a').on('click', function (e) {
      e.preventDefault();
      var targetSelector = NexT.utils.escapeSelector(this.getAttribute('href'));
      var offset = $(targetSelector).offset().top;
      hasVelocity ?
        html.velocity('stop').velocity('scroll', {
          offset: offset  + 'px',
          mobileHA: false
        }) :
        $('html, body').stop().animate({
          scrollTop: offset
        }, 500);
    });

    // Expand sidebar on post detail page by default, when post has a toc.
    NexT.motion.middleWares.sidebar = function () {
      var $tocContent = $('.post-toc-content');

      if (CONFIG.sidebar.display === 'post' || CONFIG.sidebar.display === 'always') {
        if ($tocContent.length > 0 && $tocContent.html().trim().length > 0) {
          NexT.utils.displaySidebar();
        }
      }
    };
  });
</script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=0.5.0"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"joshuashaw"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
  





  
  
  

  


</body>
</html>
